import { app, BrowserWindow, dialog, ipcMain, Menu } from "electron";
import fs from 'fs';
import Fastify from 'fastify';
import fastifyCors from '@fastify/cors';
import path from "path";
import { getNowTime_yyyyMMddHHmmss, getSysData } from './src/utils/time'
import pngToIco from 'png-to-ico'

console.log("🚀🚀🚀🚀🚀 ~ file: index.ts ~ line 52 ~ app.whenReady ~ optimizer");

/*********************************接口***********************************/

const fastify = Fastify();
const PORT = 16783;

// 启用 CORS
fastify.register(fastifyCors, {
  origin: true // 允许所有源
});

// 转码
fastify.get('/api/convertVideo', async (request, reply) => {
  // 原始数据
  let inputFile = request.query.inputFile;
  // 解码后数据
  let outputFile = request.query.outputPath;
  // 获取文件名和扩展名
  const fileName = path.parse(inputFile).name; // 获取文件名，不包括扩展名
  // 如果没有指定存储地址，就用原始数据地址
  if (request.query.outputPath == "") outputFile = path.dirname(inputFile);
  outputFile = outputFile + path.sep + fileName + "_" + getSysData() + ".ico";

  inputFile = inputFile.replace(/\\\\/g, '\\');
  outputFile = outputFile.replace(/\\\\/g, '\\');

  console.log("┏━━━━━━━━━━━━");
  console.log("输入", inputFile);
  console.log("输出", outputFile);
  console.log("┗━━━━━━━━━━━━");
  return await convertVideo(inputFile, outputFile);
});
// 转码
fastify.get('/api/getMp4FilesInfoOld', async (request, reply) => {
  let folderPath = request.query.folderPath;
  let data = getMp4FilesInfoOld(folderPath);
  return { path: folderPath, data: data };
});
// 转码
fastify.get('/api/getMp4FilesInfoNow', async (request, reply) => {
  let folderPath = request.query.folderPath;
  let data = getMp4FilesInfoNow(folderPath);
  return { path: folderPath, data: data };
});

/*************************windows操作***********************************/

fastify.get('/api/operate', async (request, reply) => {
  let operate = request.query.operate;
  console.log("operate=>", operate);
  if (operate === "0") {
    //缩小
    win.minimize();
  } else if (operate === "1") {
    // 放大
    if (win?.isMaximized()) {
      win.unmaximize();
    } else {
      win?.maximize();
    }
  } else if (operate === "2") {
    // 关闭
    win.close();
  } else {
    // 调试
    win.webContents.openDevTools();
  }
  return { code: 200, message: '操作成功' };
});
/************************************************************/

// 启动 Fastify 服务器
const startFastify = async () => {
  try {
    await fastify.listen(PORT);
    console.log(`Server is running at http://localhost:${PORT}`);
  } catch (err) {
    console.error(err);
    process.exit(1); // 如果发生错误，则退出进程
  }
};

// 南京、西安项目=》解密的两种方式
const convertVideo = async (inputFile, outputFile) => {
  pngToIco(inputFile)
    .then(buf => {
      fs.writeFileSync(outputFile, buf);
    })
    .catch(console.error);
  return {  code: 200, message: "转码完成" };
}
/*********************************接口***********************************/

let win: BrowserWindow | null = null;

const createWindow = async () => {
  await startFastify();
  win = new BrowserWindow({
    width: 800, height: 630, frame: false, // 这里设置为 false 表示无边框窗口
    webPreferences: {
      webSecurity: false, // 允许加载本地文件（开发环境）
      contextIsolation: false, // 是否开启隔离上下文
      nodeIntegration: true, // 渲染进程使用Node API
      preload: path.join(__dirname, "./preload.js") // 需要引用js文件
    }, icon: './public/images/home/logo.ico',// 图标 /public/images/home/
    title: 'png转ico'
  })

  //首页ip地址
  if (app.isPackaged) {
    win.loadURL(`file://${path.join(__dirname, '../dist-electron/index.html')}`);
  } else {
    win.loadURL("http://localhost:16282/#/")// 本地启动的vue项目路径。注意：vite版本3以上使用的端口5173；版本2用的是3000
  }

  const template = [{
    label: '调试', click: () => {
      win.webContents.openDevTools();
    }
  }];
  Menu.setApplicationMenu(Menu.buildFromTemplate(template)); // 设置菜单
}

app.whenReady().then(async () => {

  await createWindow() // 创建窗口
  app.on("activate", async () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      await createWindow()
    }
  })
})


// 获取原始数据
ipcMain.handle('select-Folder-Mp4-Old', async () => {
  const result = await dialog.showOpenDialog({
    properties: ['openDirectory']
  });
  if (result.canceled) {
    return { path: "", data: [] };
  } else {
    // 文件夹路径
    const folderPath = result.filePaths[0];
    let data = getMp4FilesInfoOld(folderPath);
    return { path: folderPath, data: data };
  }
});


// 获取转码后的数据【解密】
ipcMain.handle('select-Folder-Mp4-Now', async () => {
  const result = await dialog.showOpenDialog({
    properties: ['openDirectory'] // 只允许选择文件夹
  });

  if (result.canceled) {
    return { path: "", data: [] };
  } else {
    const folderPath = result.filePaths[0];
    let data = getMp4FilesInfoNow(folderPath);
    return { path: folderPath, data: data };
  }
});

// 递归获取所有原始 mp4 文件信息
const getMp4FilesInfoOld = (dir) => {
  let results = [];
  const files = fs.readdirSync(dir);
  for (const file of files) {
    if (path.extname(file).toLowerCase() === '.png') {
      const filePath = path.join(dir, file);
      const stat = fs.statSync(filePath);
      // 如果是 mp4 文件，获取信息
      results.push({
        path: filePath,
        size: (stat.size / 1024).toFixed(2),
        creationTime: getNowTime_yyyyMMddHHmmss(stat.birthtime)
      });
    }
  }
  // 排序
  results.sort((a, b) => a.path - b.path);
  return results;
};

// 递归获取所有已解密的mp4 文件信息
const getMp4FilesInfoNow = (dir) => {
  let results = [];
  const files = fs.readdirSync(dir);
  for (const file of files) {
    if (path.extname(file).toLowerCase() === '.ico') {
      const filePath = path.join(dir, file);
      const stat = fs.statSync(filePath);
      // 如果是 mp4 文件，获取信息
      results.push({
        path: filePath,
        size: (stat.size / 1024).toFixed(2),
        creationTime: getNowTime_yyyyMMddHHmmss(stat.birthtime)
      });
    }
  }
  // 排序
  results.sort((a, b) => a.path - b.path);
  return results;
};
/***********ICO转Png***********/

ipcMain.handle('convert-to-ico', async (event, files: string[]) => {

  const results = { success: [], failed: [] }

  for (const file of files) {
    try {
      const outputName = `${path.basename(file, '.png')}.ico`
      const outputPath = path.join(await getOutputDir(), outputName)

      pngToIco(file)
        .then(buf => {
          fs.writeFileSync(outputPath, buf);
        })
        .catch(console.error);

      results.success.push(outputPath)
    } catch (error) {
      console.error(`转换失败: ${file}`, error)
      results.failed.push(file)
    }
  }
  return results
})

// 选择输出目录
async function getOutputDir() {
  const result = await dialog.showOpenDialog({
    properties: ['openDirectory']
  })
  return result.filePaths[0] || ''
}